package whu.cn.whushare.ui.main.known;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.VolleyError;
import com.androidplus.util.ViewMapping;
import com.androidplus.util.ViewMappingUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

import whu.cn.whushare.R;
import whu.cn.whushare.bean.User;
import whu.cn.whushare.common.Constants;
import whu.cn.whushare.net.DownloadParams;
import whu.cn.whushare.net.Downloader;
import whu.cn.whushare.ui.common.BaseActivity;
import whu.cn.whushare.ui.common.LoadingHelper;
import whu.cn.whushare.ui.main.known.adapter.SearchQuestionAdapter;
import whu.cn.whushare.ui.main.known.bean.QuestionDetail;
import whu.cn.whushare.ui.main.known.bean.SearchQuestion;
import whu.cn.whushare.util.SetOnClickUtil;
import whu.cn.whushare.util.Utils;

@ViewMapping(id = R.layout.activity_known_question_list)        //获取QuestionListActivity的布局文件
public class QuestionListActivity extends BaseActivity {
	private LoadingHelper mLoadingHelper;

	private int mCurrentPage = 1;

    private String mQuestionId;
	@ViewMapping(id = R.id.question_list)               //获取问题列表视图
	private PullToRefreshListView mRefreshListView;

	private SearchQuestionAdapter mAdapter;
	private List<SearchQuestion> mQuestionTitles = new ArrayList<>();   //问题标题列表
    private String mQuery;      //问题搜索字符串

    //获取跳转到当前activity的intent信息
	public static Intent getStartIntent(Context context, String question) {
		Intent i = new Intent(context, QuestionListActivity.class);
		i.putExtra(Constants.INTENT_EXTRA_QUESTION, question);
		i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		return i;
	}

    /**
     * 发出搜索问题的请求
     * @param query - 搜索字符串
     * @param page - 当前页面
     * @param pageSize - 每页显示问题数目
     */
	protected void requestSearchQuestion(String query, int page, int pageSize) {
            mLoadingHelper.showLoadingView(false);  //显示正在加载的页面
			Downloader.getInstance(this).getQueryQuestionsList(query, page, pageSize, this, page);

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		initView();
	}

    /**
     * 对activity加载时的页面进行初始化
     */
	private void initView() {
		View root = ViewMappingUtil.mapView(this, this);    //将布局文件与当前activity一一映射
		getTopBar(root);                                    //获取顶部菜单条
        SetOnClickUtil.registerOnClick(this);               //为当前activity中所声明的域对象设置OnClickListener
		mTopBar.searchLayout.setVisibility(View.VISIBLE);
		initLoadingHelper();
		initListView();
		mTopBar.searchView.requestFocus();          //请求聚焦
		mTopBar.searchView.setSelected(true);       //设置searchView为已选中状态
		mTopBar.searchTxt.setOnClickListener(this);
	}

    //对问题列表显示视图进行初始化
	private void initListView() {
		mAdapter = new SearchQuestionAdapter(this, mQuestionTitles);
        mRefreshListView.setAdapter(mAdapter);
		mRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);     //设置只允许用户从底部刷新页面
		mRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> listViewPullToRefreshBase) {
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> listViewPullToRefreshBase) {
				if (mQuestionTitles.size() >= mTotal) {
					Utils.setRefreshLabelToLast(QuestionListActivity.this, mRefreshListView);   //显示“已经是最后一页”提示
					//0.5s后查看刷新是否完成
                    new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							mRefreshListView.onRefreshComplete();
						}
					}, 500);
				} else {
					requestSearchQuestion( mQuery, mCurrentPage + 1, 10);
				}
			}
		});

        //当问题列表中有问题被选中时跳转到问题详情页面
        mRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               SearchQuestion searchQuestion = (SearchQuestion)mAdapter.getItem(position - 1);
               mQuestionId=searchQuestion.question.getId();
               saveInvite();
            }
        });
    }
    private void saveInvite() {
      startActivityForResult(QuestionDetailActivity.getStartIntent(this,mQuestionId),1);
    }

    private void initLoadingHelper() {
		mLoadingHelper = new LoadingHelper(new View.OnClickListener() {
			@Override
            //设置retry动作发生时，请求搜索问题
			public void onClick(View v) {
                requestSearchQuestion(mQuery,mCurrentPage,10);
			}
		});
		mLoadingHelper.onCreateView(LayoutInflater.from(this), mRefreshListView);   //创建视图
	}

    //更新页面视图
	private void updateView(List<SearchQuestion> searchQuestions) {
		if (mCurrentPage == 1) {
			mQuestionTitles.clear();
            Utils.resetRefreshLabel(this, mRefreshListView);    //重置刷新标志
		}
		if (searchQuestions.size() == 0) {
			toast("无记录");
		} else {
			mQuestionTitles.addAll(searchQuestions);
		}
	}

	@Override
    /**
     * 搜索问题成功时调用该方法
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param obj -
     * @see whu.cn.whushare.net.NetResponseListener#onSuccess(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result<T>, java.lang.Object)
     */
	public <T> void onSuccess(DownloadParams.PARSING_TYPE type, T response, Object obj) {
		super.onSuccess(type, response, obj);
        mRefreshListView.onRefreshComplete();
		mLoadingHelper.showContentView();

		if (response != null) {
            mCurrentPage = (int) obj;

			updateView((List<SearchQuestion>) response);
		} else {
			toast("无记录");
		}
	}

	@Override
    /**
     * 搜索问题失败时调用该方法
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param error -
     * @see whu.cn.whushare.net.NetResponseListener#onFail(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result, com.android.volley.VolleyError)
     */
	public void onFail(DownloadParams.PARSING_TYPE type, VolleyError error) {
		super.onFail(type, error);
		mLoadingHelper.showRetryView();         //搜索失败时调用retry视图
	}

	@Override
    //当用户点击“搜索”按钮时调用该方法，对“问题搜索”事件进行处理
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.searchTxt:
			mQuery = mTopBar.searchView.getQuery().toString();      //搜索问题字符串
            System.out.print(mQuery);
			if (TextUtils.isEmpty(mQuery)) {
				toast(R.string.no_query);
			} else {
				requestSearchQuestion(mQuery, 1, 10);
			}
		}
	}
}
